﻿using System;
using System.IO;
using Microsoft.Xna.Framework.Audio;
using System.Threading;
namespace Morse
{
    public class Sound
    {
        public static SoundEffectInstance GetSount(int vol)
        {
            var sampleRate = 8000;
            var rate = 800D;
            vol = Math.Min(vol, 10);
            vol = Math.Max(vol, 0);
            var time = 10;

            var count = SoundEffect.GetSampleSizeInBytes(TimeSpan.FromMilliseconds(time), sampleRate, AudioChannels.Mono);
            var mes = new MemoryStream(count);
            var bw = new BinaryWriter(mes);
            for (int i = 0; i < count / 2; i++)
            {
                var v = Math.Sin(rate / sampleRate * Math.PI * 2 * i) + 1;
                v *= ushort.MaxValue / 2;
                bw.Write((ushort)v);
            }
            var bf = mes.GetBuffer();
            var sound = new SoundEffect(bf, sampleRate, AudioChannels.Mono);
            mes.Dispose();
            var si = sound.CreateInstance();
            si.IsLooped = true;
            si.Volume = vol / 10f;
            return si;
        }

        public static SoundTask Play(string code)
        {
            var task = new SoundTask();
            task.Play(code);
            return task;
        }
    }
}
